package com.demo.service.impl;

import com.demo.common.util.StringUtil;
import com.demo.dao.CommonDao;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基础service
 *
 * @Created by lj on 2016/9/13.
 */
public class BaseService {


    /**
     * 通用更新语句sqlID
     */
    private final static String COMMONMAPPER_UPDATEBYCONDITION = "com.demo.dao.CommonMapper.updateByCondition";

    /**
     * 通用查询语句ID
     */
    private final static String COMMONMAPPER_SELECTSINGLECOLUMN = "com.demo.dao.CommonMapper.selectColumns";

    /**
     * 通用公共Dao
     */
    @Resource
    public CommonDao commonDao;

    public List selectColumns(String tableName, String column, Object[] condition) {
        Map<String, Object> conditionMap = new HashMap<String, Object>();
        if ((condition.length) % 2 == 0) {
            for (int i = 0; i < condition.length; i++) {
                conditionMap.put((String) condition[i++], condition[i]);
            }
        } else {
            throw new RuntimeException("【条件参数】数量不正确！");
        }

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conditionMap", conditionMap);
        params.put("tableName", tableName);
        params.put("column", column);
        List list = commonDao.selectColumns("com.demo.dao.CommonMapper.selectSingleColumn", params);
        if (StringUtil.isEmptyList(list)) return null;
        return list;
    }

    /**
     * 根据条件查询一个值
     *
     * @param tableName
     * @param column    column
     * @param condition condition1, condition1Value, condition2, condition2Value...
     * @return
     */
    public Object selectSingleColumn(String tableName, String column, Object... condition) {
        List list = this.selectColumns(tableName, column, condition);
        if (StringUtil.isEmptyList(list)) return null;
        return list.get(0);
    }

    /**
     * 根据条件查询一组值
     *
     * @param tableName
     * @param column    column1, column2
     * @param condition condition1, condition1Value, condition2, condition2Value...
     * @return
     */
    public Object[] selectMultipleColumn(String tableName, String column, Object... condition) {
        List list = this.selectColumns(tableName, column, condition);
        if (StringUtil.isEmptyList(list)) return null;
        return list.toArray();
    }
}
